using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using FtpWorkerRole.FtpServer;

namespace FtpWorkerRole
{
    public class WorkerRole : RoleEntryPoint
    {
        private CloudFtpServer ftpServer;

        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.WriteLine("$projectname$ entry point called", "Information");
            ftpServer.listen();
            while (true)
            {
                Thread.Sleep(10000);
                Trace.WriteLine("Working", "Information");
            }
        }

        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 36;

            // Add the perf counters
            var config = DiagnosticMonitor.GetDefaultInitialConfiguration();
            var cloudStorageAccount =
                CloudStorageAccount.Parse(
                  RoleEnvironment.GetConfigurationSettingValue(
                  "Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"));

            config.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
           
            List<string> testSpecifiers = PerformanceSpecifier.GetSpecifiers();
            foreach (string s in testSpecifiers)
            {
                config.PerformanceCounters.DataSources.Add(
                    new PerformanceCounterConfiguration
                    {
                        CounterSpecifier = s,
                        SampleRate = TimeSpan.FromSeconds(30)
                    });
            }
            DiagnosticMonitor diagMonitor = DiagnosticMonitor.Start(cloudStorageAccount, config);

            if (ftpServer == null)
            {
                ftpServer = new CloudFtpServer(2121);
            }
            return base.OnStart();
        }
    }
}
